<template>
  <div>
    <el-card v-loading="loading">
      <div class="form">
        <el-form :inline="true">
          <el-form-item label="实验类型">
            <el-select v-model="form.experimentType" placeholder="请选择--" @change="handleExperitypeChange">
              <el-option v-for="item in optionsList.experimentType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="实验室">
            <el-select v-model="form.lab" placeholder="请选择--">
              <el-option v-for="item in optionsList.lab" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="第几周">
            <el-select v-model="form.week" placeholder="请选择--">
              <el-option label="第一周" value="first"></el-option>
              <el-option label="第二周" value="second"></el-option>
              <el-option label="第三周" value="third"></el-option>
            </el-select>
          </el-form-item>
          <el-date-picker
            v-model="pickerOptions2.sDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions2">
          </el-date-picker>

          <el-form-item>
            <el-button type="primary">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 15px">
        <el-table :data="tableData" max-height="650" border style="width: 100%">
          <el-table-column fixed type="index" width="68" align="center">
          </el-table-column>
          <el-table-column fixed label="日期" width="95" align="center">
            <template slot-scope="scope">
              {{ scope.row.day }}
            </template>
          </el-table-column>
          <el-table-column v-for="iitem in timeSoltArr" :key="iitem.id" :label="iitem.timeSlotName" min-width="280" align="center" :render-header="labelHead">
            <template slot-scope="scope">
              <div v-for="item in scope.row.labArr" :key="item.id">
                <div v-if="item.timeSlotId === iitem.id">
                  <div v-if="item.type === 1" style="color: #000">
                    {{item.labName}}：已排课
                  </div>
                  <div v-else-if="item.type === 0">
                    <div v-if="item.maxNumber === item.appointmentNum" style="color: red">
                      {{item.labName}}：预约已满
                    </div>
                    <div v-else>
                      <router-link
                        :to="{
                          path: `/studentAppoint/infor/${item.id}/${form.experimentType}`
                        }"
                      >
                        <el-button type="text">
                          {{item.name}}：{{item.appointmentNum}}人已预约（剩余：{{item.maxNumber}}）
                        </el-button>
                      </router-link>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 底部翻页器，超过一页的时候显示 -->
      <div v-if="page.total > page.pageSize" class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :pager-count="5"
          :total="page.total"
          :page-size="page.pageSize"
          :current-page="page.currentPage"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
// import axios from 'axios'
export default {
  data() {
    return {
      pickerOptions2: {
        // sDate: [new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 7), new Date()]
      },

      loading: true,
      form: {
        experimentType: '',
        // experiment: '',
        lab: '',
        week: ''
      },
      tableData: [], // 列表中的数据
      optionsList: {
        experimentType: [],
        // experiment: [],
        lab: []
      },
      page: {
        total: 10,
        currentPage: 1,
        pageSize: 10
      },
      timeSoltArr: [] // 时间段列表
    }
  },
  created() {
    this.getExperiType()
    // this.getAll()
  },
  methods: {
    getExperiType() { // 获取实验类型列表
      request.get('/labs/experitype/page', { params: {
        current: 1,
        size: 1000
      }}).then(res => {
        if (!res.code) {
          this.optionsList.experimentType = res.content.records
          this.form.experimentType = res.content.records[0].id
          this.getLabAppoinentCondition()
        }
      })
    },
    handleExperitypeChange() {
      this.getLabAppoinentCondition()
    },
    async getLabAppoinentCondition() { // 查询实验室所有预约情况
      this.loading = true
      try {
        await request.get('/items/labAppointmentCondition', { params: {
          current: 1,
          size: 1000,
          timeSlot: this.pickerOptions2.sDate,
          experimentId: this.form.experimentType
        }}).then(res => {
          var dayArr = []
          var dayArrFilter = []
          for (let i = 0, len = res.content.records.length; i < len; i++) {
            dayArr.push(res.content.records[i].day)
          }
          dayArrFilter = dayArr.filter((element, index, self) => { // 当前元素值（必须）、当前元素索引值、当前元素属于的数组对象
            return self.indexOf(element) === index
          })
          for (let j = 0, len = dayArrFilter.length; j < len; j++) {
            if (this.tableData[j] !== {}) {
              this.tableData[j] = {}
            }
            this.tableData[j].day = dayArrFilter[j]
            this.tableData[j].labArr = []
          }
          for (let m = 0, len = res.content.records.length; m < len; m++) {
            for (let n = 0; n < this.tableData.length; n++) {
              if (this.tableData[n].day === res.content.records[m].day) {
                const { labId, timeSlotId, name, maxNumber, appointmentNum, type, id } = res.content.records[m] // type:0可预约，1已排课，2其他
                this.tableData[n].labArr.push({ labId, timeSlotId, name, maxNumber, appointmentNum, type, id })
              }
            }
          }
        })
        const data = await request.get('/items/labTimerSlot')
        if (!data.code) {
          this.timeSoltArr = data.content
        }
      } catch (err) {
        console.log(err)
      }
      this.loading = false
    },
    // getAll() { // 并发执行上述两个操作
    //   axios.all([this.getLabAppoinentCondition(), this.getLabTimeSolt()]).then(axios.spread((acct, acct2) => {
    //     console.log('描述：', acct, acct2)
    //   }))
    // },
    labelHead(h, { column, $index }) {
      return h('div', [
        h('div', { class: 'label-heade' }, this.timeSoltArr[$index - 2].timeSlotName),
        h('div', { class: 'label-heade-time' }, `${this.timeSoltArr[$index - 2].startTime}——${this.timeSoltArr[$index - 2].endTime}`)
      ])
    },
    handleCurrentChange(val) {
      console.log('当前页是：', val)
    },
    editInfor(id) {
      this.$router.push({
        path: `/studentAppoint/infor/${id}`,
        params: {
          typeId: this.form.experimentType
        }
      })
    }
  }
}
</script>

<style scoped>
.form {
  background-color: #f7f7f7;
  padding-left: 15px;
  padding-top: 20px;
}
.pagination {
  float: right;
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>

<style>
.label-heade {
  display: block !important;
}
.label-heade-time {
  font-family: 'Helvetica';
}
</style>
